<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="城市等级">
        <el-select v-model="queryParams2.cityRank" placeholder="请选择"  @input=getList>
          <el-option
            v-for="item in cityRankList2"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="城市">
        <el-select v-model="registerCity" multiple placeholder="请选择" @input=getList>
          <el-option
            v-for="item in cityRankList3"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="行政区">
        <el-select v-model="registerArea" multiple placeholder="请选择" @input=getList>
          <el-option
            v-for="item in cityRankList4"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>

      <br>

      <el-form-item label="注册时间" prop="registDate">
        <div class="block">
          <el-date-picker
            v-model="registDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            @input="getList"
          ></el-date-picker>
        </div>
      </el-form-item>

      <el-form-item label="用户类型" prop="customerType" >
        <el-checkbox-group :min="1" v-model="customerType" @input="getList">
          <el-checkbox-button v-for="city in cityOptions" :label="city.value" :key="city.value">
            {{ city.label }}
          </el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="" prop="showDate">
        <span class="demonstration"></span>
        <el-date-picker
          v-model="queryParams.showDate"
          type="month"
          placeholder="选择月份"
          value-format="yyyy-MM"
          @input="setRegistDateRange"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:customer:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div id="chart" style="width: 100%; height: 500px;"></div>

  </div>
</template>

<script>
import * as echarts from 'echarts';
import { UserRegistrationlist } from "@/api/basicFeatures/userManagement/userRegistration/userregistration";
import { listCityRank } from "@/api/cityRank/cityRank";
const a= ["一线城市","二线城市","三线城市"];
export default {
  name: "Customer",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      customerList: [],
      // 接收城市等级表格数据
      cityRankList:[],
      //城市等级数据 一线城市 二线城市 三线城市
      cityRankList2:a,
      //城市数据 去重 展示
      cityRankList3:[],
      //行政区数据 去重 展示
      cityRankList4:[],
      //城市数据  数据绑定
      registerCity:[],
      //县级行政区数据 数据绑定
      registerArea:[],
      //用户类型数据 数据绑定
      customerType: [1,2],
      //用户类型数据
      cityOptions: [
        { label: '乘客', value: 1 },
        { label: '司机', value: 2 }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户信息表 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        abc:'',
        customerType: null,
        startDate:'',
        endDate:'',
        registerCity:'',
        registerArea:'',
        showDate:''
      },
      //注册时间数据
      registDate:'',
      // // 城市等级表    查询参数
      queryParams2: {
        pageNum: 1,
        pageSize: 1000,
        cityRank:'',
        city:''
      },
      pickerOptions: {
        pickerOptions: {
          disabledDate: this.getDefaultDisabledDate()
        },
      }


    };
  },
  mounted() {
    //获取当前日期 赋值给showDate字符串 格式为 yyyy-MM
    this.queryParams.showDate = new Date().toLocaleDateString().replace(/\//g, '-').slice(0,7);
    this.setRegistDateRange();
  },
  methods: {
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;

     // 调用城市接口
      listCityRank(this.queryParams2).then(response => {
        //如果接口调用正确
        if (response.code==200){
          //接收返回响应
          this.cityRankList = response.rows;
          //接收返回响应中的城市数据 去重
          this.cityRankList3=Array.from(new Set(this.cityRankList.map(item => item.city.trim())));
          //接收返回响应中的县级行政区数据 去重
          this.cityRankList4=Array.from(new Set(this.cityRankList.map(item => item.administrative_districts.trim())));
          //判断查询参数是否为空
          if(this.queryParams2.cityRank!=''){
            //将this.cityRankList中的city转成字符串赋值给this.queryParams.registerCity
            this.queryParams.registerCity = Array.from(new Set(this.cityRankList.map(item => item.city.trim()))).join(',');
          }else{
            this.queryParams.registerCity='';
          }
          //判断注册城市是否有值
          if (this.registerCity.length === 0) {
          } else {
            this.queryParams.registerCity = Array.from(new Set(this.registerCity.map(item => item.trim()))).join(',');
            this.cityRankList4 = this.cityRankList
              .filter(item => this.registerCity.includes(item.city.trim()))
              .map(item => item.administrative_districts.trim());
            this.cityRankList4 = Array.from(new Set(this.cityRankList4));
          }
          //判断注册行政区是否有值
          if (this.registerArea.length === 0) {
            this.queryParams.registerArea='';
          } else {
            this.queryParams.registerArea = Array.from(new Set(this.registerArea.map(item => item.trim()))).join(',');
          }



          //判断用户类型
          if (this.customerType.length>1){
            this.queryParams.customerType = null;
          }else{
            this.queryParams.customerType = this.customerType[0];
          }



          //调用用户接口
          UserRegistrationlist(this.queryParams).then(response => {
            this.customerList = response;

            //判断注册时间
            if (this.registDate!=''){

              const wzy=this.registDate.toString();

              const dates = wzy.split(',');

              // 解析日期
              const startDate = new Date(dates[0]);
              const endDate = new Date(dates[1]);

// 确保 startDate 和 endDate 是有效的日期对象
              if (isNaN(startDate) || isNaN(endDate)) {
                console.error('无效的日期格式');
                return;
              }

// 生成日期范围内的所有日期
              function getDatesInRange(startDate, endDate) {
                const dateArray = [];
                const currentDate = new Date(startDate);

                while (currentDate <= endDate) {
                  dateArray.push(new Date(currentDate).toISOString().split('T')[0].substring(8,10));
                  currentDate.setDate(currentDate.getDate() + 1);
                }

                return dateArray;
              }

              const allDates = getDatesInRange(startDate, endDate);
              var s = dates[0].substring(8, 11)
              var e = dates[1].substring(8, 11)
              //获取数组中s到e的数据
              const lzy = this.customerList.map(item => item.numRecords);
              const a = lzy.slice(s-1,e)
              const b= allDates;
              const c= Array.from(new Set(this.customerList.map(item => item.day.substring(5, 7))))
              this.initChart(a,b,c);
            }
            this.loading = false;
          });
        }
      });

    },
    /** 初始化图表 */
    initChart(a, b, c) {
      var echart = echarts.init(document.getElementById("chart"));

      // 计算增长率
      function calculateGrowthRates(data) {
        const growthRates = [];
        for (let i = 1; i <= data.length; i++) {
          const current = data[i];
          const previous = data[i - 1];
          if (previous === 0 && current === 0) {
            growthRates.push(0); // 上期数据为0，或本期数据为0，无法计算增长率
          }else if (previous ===0 && current !==0){
            growthRates.push(100);
          }
          else {
            growthRates.push(((current - previous) / previous) * 100);
          }
        }
        return growthRates;
      }

      const growthRates = calculateGrowthRates(a);
      const declineRates = growthRates.map(rate => rate !== null ? -rate : null);

      // 调整增长趋势和下降趋势的数据点到前一天
      const adjustedGrowthRates = [0, ...growthRates.slice(0, -1)];
      const adjustedDeclineRates = [0, ...declineRates.slice(0, -1)];

      var option = {
        title: {
          text: c + '月注册人数'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            if (!params || params.length === 0) {
              return ''; // 没有数据时返回空字符串
            }

            let tooltipHtml = `<div style="text-align: center">日期:${c+'-'+params[0].name}`;
            params.forEach(param => {
              const value = param.value !== null && param.value!= null ? (param.value) : '-';
              if (param.seriesName === '注册人数') {
                tooltipHtml += `<div><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>${param.seriesName}: ${value}</div>`;
              } else if (param.seriesName === '增长趋势') {
                if (value !== '-') {
                  const growthText = param.value >= 0 ? '注册人数增加' : '注册人数下降';
                  tooltipHtml += `<div><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>${param.seriesName}: ${formatValue(value)}% (${growthText})</div>`;
                }
              } else if (param.seriesName === '下降趋势') {
                if (value !== '-') {
                  const declineText = param.value >= 0 ? '注册人数下降' : '注册人数增加';
                  tooltipHtml += `<div><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>${param.seriesName}: ${formatValue(value)}% (${declineText})</div>`;
                }
              }
            });
            tooltipHtml += '</div>';
            return tooltipHtml;
          }
        },
        legend: {
          data: ["注册人数", "增长趋势", "下降趋势"],
          bottom: 0
        },
        xAxis: {
          data: b
        },
        yAxis: [
          {
            name: '注册人数',
            type: 'value'
          },
          {
            name: '增长率 (%)',
            type: 'value',
            position: 'right',
            min: -100,
          }
        ],
        series: [
          {
            name: "注册人数",
            type: "bar",
            data: a
          },
          {
            name: "增长趋势",
            type: "line",
            data: adjustedGrowthRates,
            yAxisIndex: 1,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              color: 'green'
            },
            z: 10 // 将折线图点放在柱状图的上面
          },
          {
            name: "下降趋势",
            type: "line",
            data: adjustedDeclineRates,
            yAxisIndex: 1,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              color: 'red'
            },
            z: 10 // 将折线图点放在柱状图的上面
          }
        ]
      };

      echart.setOption(option);

      // 辅助函数：格式化数值，保留两位小数
      function formatValue(value) {
        if (value === null) {
          return '无数据';
        }
        if (typeof value === 'number') {
          return value.toFixed(2);
        }
        return value;
      }
    },
    /** 初始化日期选择器 */
    getDefaultDisabledDate() {
      const now = new Date();
      const currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      const currentMonthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      return time => {
        return time.getTime() < currentMonthStart.getTime() || time.getTime() > currentMonthEnd.getTime();
      };
    },
    /** 更新注册时间选择范围 */
    setRegistDateRange() {
      if (this.queryParams.showDate) {
        const [year, month] = this.queryParams.showDate.split('-').map(Number);
        const startDate = new Date(year, month - 1, 2);
        const endDate = new Date(year, month, 1);

        this.registDate = [startDate.toISOString().split('T')[0], endDate.toISOString().split('T')[0]];

        const startDate2 = new Date(year, month - 1, 1);
        const endDate2 = new Date(year, month, 0);

        this.pickerOptions.disabledDate = time => {
          return time.getTime() < startDate2.getTime() || time.getTime() > endDate2.getTime();
        };

        // 如果当前选择的注册时间不在新选择的月份范围内，重置注册时间
        if (this.registDate.length === 2) {
          const [start, end] = this.registDate;
          if (new Date(start).getTime() < startDate.getTime() || new Date(end).getTime() > endDate.getTime()) {
            this.registDate = [startDate.toISOString().split('T')[0], endDate.toISOString().split('T')[0]];
          }
        }
      } else {
        this.registDate = [];
        this.pickerOptions.disabledDate = time => true;
      }

      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.registerCity=[];
      this.registerArea=[];
      this.customerType=[1,2];
      this.queryParams.pageNum = 1;
      this.queryParams.customerType = null;
      this.queryParams.registerCity='';
      this.queryParams.registerArea='';
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/customer/userRegistrationListExport', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}牛婶打车app用户${this.queryParams.showDate}注册数据.xlsx`)
    }
  }
};
</script>

<style>

.el-checkbox-button.is-disabled .el-checkbox-button__inner {
  color: white;
  cursor: not-allowed;
  background-image: none;
  background-color: #00afff;
  border-color: #00afff;
  -webkit-box-shadow: none;
  box-shadow: none;
}
</style>
